package com.yaolifei.flower.core.impl;

import java.sql.Connection;
import java.util.List;

import org.nutz.dao.ConnCallback;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.MappingField;
import org.nutz.dao.impl.DaoSupport;
import org.nutz.dao.impl.entity.NutEntity;
import org.nutz.dao.impl.entity.field.NutMappingField;
import org.nutz.dao.jdbc.Jdbcs;

import com.yaolifei.flower.core.Model;
import com.yaolifei.flower.core.ModelColumn;

public class ModelNutEntityMaker {

	private DaoSupport support;

	public ModelNutEntityMaker(DaoSupport support) {
		this.support = support;
	}

	public Entity<Object> makeEntity(Model model) {
		final NutEntity<Object> en = new NutEntity<Object>(Object.class);
		en.setTableName(model.getPhysicalName());
		en.setViewName(model.getPhysicalName());

		List<ModelColumn> columns = model.getColumns();
		for (ModelColumn c : columns) {
			makeFieldMapping(en, c);
		}
		// en.checkCompositeFields(null);

		// 最后在数据库中验证一下实体各个字段
		support.run(new ConnCallback() {
			public void invoke(Connection conn) throws Exception {
				support.getJdbcExpert().setupEntityField(conn, en);
			}
		});

		// 搞定返回
		return en;
	}

	private MappingField makeFieldMapping(Entity<Object> en, ModelColumn c) {
		// 是实体字段
		NutMappingField ef = new NutMappingField(en);

		if (c.isAutoIncrease()) {
			ef.setAsAutoIncreasement();
			ef.setAsId();
		}
		if (!c.isNullable()) {
			ef.setAsNotNull();
		}
		// ef.setName(c.getColumnName());

		ef.setType(c.getColumnType().getJavaClass());
		ef.setColumnName(c.getPhysicalName());

		// 猜测一下数据库类型
		Jdbcs.guessEntityFieldColumnType(ef);
		ef.setAdaptor(support.getJdbcExpert().getAdaptor(ef));

		if (en instanceof NutEntity) {
			((NutEntity<Object>) en).addMappingField(ef);
		}
		return ef;
	}

}
